package com.zangchat.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.common.core.controller.BaseController;
import com.common.core.domain.AjaxResult;
import com.egzosn.pay.common.api.PayService;
import com.zangchat.config.WxPayDataConfig;
import com.zangchat.domain.ChatLogThirdpay;
import com.zangchat.service.IChatLogThirdpayService;
import com.zangchat.service.IChatUsersRechargeService;
import com.zangchat.service.IChatUsersService;
import com.zangchat.service.IPersonalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

/**
 * 个人首页Controller
 *
 * @author wudi
 * @date 2020-07-15
 */
@RestController
@RequestMapping("/zangchat/personal")
public class personalController extends BaseController{

    @Autowired
    private IPersonalService personalService;
    @Autowired
    private IChatLogThirdpayService chatLogThirdpayService;

    @Autowired
    private IChatUsersRechargeService chatUsersRechargeService;
    /**
     * 个人中心 账户余额及关注数量
     * @param userId
     * @return
     */
    @RequestMapping("/inTopersonal")
    public AjaxResult inTopersonal(@ModelAttribute("userId") Long userId){
       return personalService.inTopersonal(userId);
    }

    /**
     * 用户充值 生成订单并吊起App
     * @param userId 用户id
     * @param cash 充值金额
     * @param payType 支付方式 '充值方式1:线下现金支付2.支付宝3.微信4银联快捷5.第三方支付',
     * @return
     */
    @RequestMapping("/recharge")
    public AjaxResult recharge(Long userId, BigDecimal cash,Integer payType ){
       return personalService.recharge( userId, cash,payType );
    }
    /**
     * 支付宝回调
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/aliNotifyUrl")
    public void aliNotifyUrl(HttpServletRequest request) throws IOException {
        Map<String, String> params = new TreeMap<String,String>();
        Map<String, String[]> parameterMap =request.getParameterMap();
        for (Map.Entry<String,  String[]> entry  :  parameterMap.entrySet()) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            String valueStr = "";
            for (int i = 0,len =  values.length; i < len; i++) {
                valueStr += (i == len - 1) ?  values[i] : values[i] + ",";
            }
            if (!valueStr.matches("\\w+")){
                try {
                    if(valueStr.equals(new String(valueStr.getBytes("iso8859-1"), "iso8859-1"))){
                        valueStr=new String(valueStr.getBytes("iso8859-1"), WxPayDataConfig.CHARSET);
                    }
                } catch (UnsupportedEncodingException e) {
//                    LOG.error(e);
                }
            }
            params.put(name, valueStr);
        }
        String outTradeNo = params.get("out_trade_no");
        String totalAmount = params.get("total_amount");
        //第三方支付记录
        ChatLogThirdpay chatLogThirdpay=new ChatLogThirdpay();
        chatLogThirdpay.setOrderNo(outTradeNo);
        BaseMapper<ChatLogThirdpay> logThirdpayServiceBaseMapper = chatLogThirdpayService.getBaseMapper();
        ChatLogThirdpay logThirdpay = logThirdpayServiceBaseMapper.selectOne(new QueryWrapper<ChatLogThirdpay>(chatLogThirdpay));
        logThirdpay.setHandleStatus(2);
        logThirdpay.setResponseTime(new Date());

        PayService service = chatUsersRechargeService.initAliPayService();
        Map param = service.getParameter2Map(request.getParameterMap(), request.getInputStream());
        logThirdpay.setResponse(param.toString());
        logThirdpayServiceBaseMapper.updateById(logThirdpay);
        if (service.verify(param)){
            System.out.println("支付成功");
            chatUsersRechargeService.doNotifyUrl(outTradeNo,totalAmount,2);
        }

    }


}
